package com.zjs.utils;

import com.zjs.common.Constants;
import com.zjs.exception.ServiceException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 导出功能类
 *
 * @author zhengJianSheng
 * @since 2023-06-19 17:40
 */
public class ExportUtil {
    private ExportUtil() {

    }


    /**
     * 导出配置sql
     *
     * @param list     集合
     * @param response 响应体
     * @param fileName 文件名称
     * @param <T>      泛型
     */
    public static <T> void exportSql(List<T> list, HttpServletResponse response, String fileName) {

        try {
            String exportSql = GenerateSqlUtil.generateExportSql(list);
            // 替换字符串中的换行符为系统默认的换行符
            exportSql = exportSql.replace("\\n", System.lineSeparator());

            response.setContentType("application/octet-stream;charset=UTF-8");
            String formattedFileName = String.format("%s-%s.sql", fileName, new SimpleDateFormat("yyyyMMdd").format(new Date()));
            formattedFileName = URLEncoder.encode(formattedFileName, StandardCharsets.UTF_8.toString());
            response.setHeader("Content-Disposition", "attachment;filename=" + formattedFileName);
            // 将字符串写入到输出流中
            response.getOutputStream().write(exportSql.getBytes());
            response.getOutputStream().flush();
            response.getOutputStream().close();

        } catch (IOException e) {
            throw new ServiceException(Constants.CODE_500, "导出sql脚本失败");
        }
    }
}
